using System;
using System.Collections.Generic;
using System.Text;

namespace Acms.Providers
{
    public class AcmsMembershipProvider : System.Web.Security.MembershipProvider
    {
        private string applicationName;
        public override string ApplicationName
        {
            get
            {
                return applicationName;
            }
            set
            {
                applicationName = value;
            }
        }

        private Bll.UserSecurity GetUser(string username)
        {
            return Bll.UserSecurity.GetByUserName(username);
        }

        private System.Web.Security.MembershipUser ConvertUser(Bll.UserSecurity user)
        {
            if (user != null)
            {
                return new System.Web.Security.MembershipUser(
                    "AcmsMembershipProvider",
                    user.UserName,
                    user.Id,
                    user.EmailAddress,
                    user.PasswordQuestion,
                    null,
                    user.Authenticated,
                    user.Locked,
                    user.Created,
                    (user.LastLogin == null ? DateTime.MinValue : user.LastLogin.Value),
                    (user.LastActivity == null ? DateTime.MinValue : user.LastActivity.Value),
                    (user.LastChangedPassword == null ? DateTime.MinValue : user.LastChangedPassword.Value),
                    (user.LastLocked == null ? DateTime.MinValue : user.LastLocked.Value)
                    );
            }
            else
            {
                return null;
            }
        }

        private System.Web.Security.MembershipUserCollection ConvertUsers(List<Acms.Bll.UserSecurity> users)
        {
            System.Web.Security.MembershipUserCollection tmp = new System.Web.Security.MembershipUserCollection();
            if (users != null)
            {
                foreach (Acms.Bll.UserSecurity user in users)
                {
                    tmp.Add(ConvertUser(user));
                }
            }
            return tmp;

        }


        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            bool ret = false;
            Bll.UserSecurity user = GetUser(username);
            if (user != null)
            {
                ret = user.SetPassword(oldPassword, newPassword);
                if (ret)
                {
                    user.Update();
                }
            }
            return ret;
        }

        public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
        {
            bool ret = false;
            Bll.UserSecurity user = GetUser(username);
            if (user != null)
            {
                ret = user.AuthenticatePassword(password);
                if (ret)
                {
                    user.PasswordQuestion = newPasswordQuestion;
                    user.PasswordAnswer = newPasswordAnswer;
                    user.Update();
                }
            }
            return ret;
        }

        public override System.Web.Security.MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out System.Web.Security.MembershipCreateStatus status)
        {
            System.Web.Security.MembershipUser tmpUser = null;
            System.Web.Security.MembershipCreateStatus tmpStatus = System.Web.Security.MembershipCreateStatus.UserRejected;

            Bll.UserSecurity user = Acms.Bll.UserSecurity.CreateInstance();
            user.UserName = username;
            user.EmailAddress = email;
            user.PasswordQuestion = passwordQuestion;
            user.PasswordAnswer = passwordAnswer;
            user.Authenticated = isApproved;
            user.SetPassword(null, password);

            //ToDo Catch Specific errors to return different status
            user.Update();
            
            tmpStatus = System.Web.Security.MembershipCreateStatus.Success;
            tmpUser = ConvertUser(user);

            status = tmpStatus;
            return tmpUser;
        }

        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            bool ret = false;
            Bll.UserSecurity user = GetUser(username);
            user.Delete();
            ret = true;
            return ret;
        }

        public override bool EnablePasswordReset
        {
            get { return true; }
        }

        public override bool EnablePasswordRetrieval
        {
            get { return false; }
        }

        public override System.Web.Security.MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            totalRecords = 0;
            List<Bll.UserSecurity> users = Bll.UserSecurity.GetAllByEmailAddressPaged(emailToMatch, null, pageIndex * pageSize, pageSize, ref totalRecords);
            return ConvertUsers(users);
        }

        public override System.Web.Security.MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            totalRecords = 0;
            List<Bll.UserSecurity> users = Bll.UserSecurity.GetAllByUsernamePaged(usernameToMatch, null, pageIndex * pageSize, pageSize, ref totalRecords);
            return ConvertUsers(users);
        }

        public override System.Web.Security.MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            totalRecords = 0;
            List<Bll.UserSecurity> users = Bll.UserSecurity.GetAllPaged(null, pageIndex * pageSize, pageSize, ref totalRecords);
            return ConvertUsers(users);
        }

        public override int GetNumberOfUsersOnline()
        {
            return Bll.UserSecurity.CountOnline();
        }

        public override string GetPassword(string username, string answer)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override System.Web.Security.MembershipUser GetUser(string username, bool userIsOnline)
        {
            return ConvertUser(Bll.UserSecurity.GetByUserName(username, userIsOnline));
        }

        public override System.Web.Security.MembershipUser GetUser(object providerUserKey, bool userIsOnline)
        {
            return ConvertUser(Bll.UserSecurity.GetById((int)providerUserKey, userIsOnline));
        }

        public override string GetUserNameByEmail(string email)
        {
            throw new Exception("The method or operation is not implemented.");
        }

        public override int MaxInvalidPasswordAttempts
        {
            get { return 3; }
        }

        public override int MinRequiredNonAlphanumericCharacters
        {
            get { return 0; }
        }

        public override int MinRequiredPasswordLength
        {
            get { return 6; }
        }

        public override int PasswordAttemptWindow
        {
            get { return 30; }
        }

        public override System.Web.Security.MembershipPasswordFormat PasswordFormat
        {
            get { return System.Web.Security.MembershipPasswordFormat.Hashed; }
        }

        public override string PasswordStrengthRegularExpression
        {
            get { return @"(?=.{6,})(?=(.*\d){1,})(?=(.*\W){1,})"; }
        }

        public override bool RequiresQuestionAndAnswer
        {
            get { return true; }
        }

        public override bool RequiresUniqueEmail
        {
            get { return true; }
        }

        public override string ResetPassword(string username, string answer)
        {
            string ret = null;
            Bll.UserSecurity user = GetUser(username);
            if (user != null)
            {
                if (user.ValidatePasswordAnswer(answer))
                {
                    ret = user.ResetPassword();
                }
            }
            return ret;
        }

        public override bool UnlockUser(string userName)
        {
            bool ret = false;
            Bll.UserSecurity user = GetUser(userName);
            if (user != null)
            {
                user.Unlock();
                user.Update();
                ret = true;
            }
            return ret;
        }

        public override void UpdateUser(System.Web.Security.MembershipUser user)
        {
            Bll.UserSecurity newUser = null;
            if (user.ProviderUserKey != null && user.ProviderUserKey is int)
            {
                newUser = Bll.UserSecurity.GetById((int)user.ProviderUserKey, user.IsOnline);
            }
            if (newUser != null)
            {
                throw new NotImplementedException();
            }
        }

        public override bool ValidateUser(string username, string password)
        {
            bool ret = false;
            Bll.UserSecurity user = GetUser(username);
            if (user != null)
            {
                ret = user.AuthenticatePassword(password);
            }
            return ret;
        }
    }
}
